package com.rongshu.view.login.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.RxHelper;
import com.rongshu.utils.SpannableStringUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.login.contract.AuthCodeLoginView;
import com.rongshu.view.login.entity.PasswordLogin;
import com.rongshu.view.login.presenter.AuthCodeLoginPresenter;
import com.rongshu.view.web.LocalWebActivity;
import com.rongshu.widget.PhoneEditText;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.utils.SPUtils;
import com.utils.Utils;
import com.utils.constants.SPKey;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import rx.Subscriber;

/**
 * 验证码登录
 */
public class VerificationCodeLoginActivity extends BaseActivity<AuthCodeLoginPresenter> implements AuthCodeLoginView {
    @BindView(R.id.phone_ed)
    PhoneEditText phoneEd;
    @BindView(R.id.txtGetVerification)
    TextView txtGetVerification;
    @BindView(R.id.protocal_switch)
    CheckBox protocalSwitch;
    @BindView(R.id.protocol_tv)
    TextView protocolTv;
    @BindView(R.id.last_login_weixin)
    ImageView lastLoginWeixin;
    @BindView(R.id.last_login_qq)
    ImageView lastLoginQq;
    //request
    private final int REQUEST_CODE = 0x01;
    //type
    private int type = 0;
    private int currentTimes = 60;
    private String netAuthCode = null;
    //permission
    private String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    protected int initLayout() {
        return R.layout.activity_verification_code_login;
    }

    @Override
    protected void initView() {
        setPresenter(new AuthCodeLoginPresenter(this), this);
        int preferences = SPUtils.getPreferences(Constant.LOGIN_WAY, 0);
        lastLoginWeixin.setVisibility(preferences == Constant.LOGIN_WAY_WECHAT ? View.VISIBLE : View.INVISIBLE);
        lastLoginQq.setVisibility(preferences == Constant.LOGIN_WAY_QQ ? View.VISIBLE : View.INVISIBLE);
        //富文本显示
        protocolTv.setText(SpannableStringUtils.addMoreForeColorSpan(protocolTv.getText().toString(),
                ContextCompat.getColor(this, R.color.color_4a4a4a_protocol), 7, 15, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //用户协议
                        Intent intent = new Intent(VerificationCodeLoginActivity.this, LocalWebActivity.class);
                        intent.putExtra(Constant.INTENT_TITLE, "用户服务协议");
                        intent.putExtra(Constant.INTENT_H5, Common.USER_AGREEMETN);
                        startActivity(intent);
                    }
                }, 16, 22, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(VerificationCodeLoginActivity.this, LocalWebActivity.class);
                        intent.putExtra(Constant.INTENT_TITLE, "隐私政策");
                        intent.putExtra(Constant.INTENT_H5, Common.PRIVACY_POLICY);
                        startActivity(intent);
                    }
                }));
        protocolTv.setMovementMethod(LinkMovementMethod.getInstance());
        protocolTv.setHighlightColor(getResources().getColor(android.R.color.transparent));
        txtGetVerification.setClickable(false);
        //默认选中协议
        protocalSwitch.setChecked(true);
        //默认显示上次登录的手机号码
        if (!TextUtils.isEmpty(SPUtils.getPreferences(SPKey.LAST_LOGIN_PHONE, ""))) {
            showKeyboard(false);
            phoneEd.setText(SPUtils.getPreferences(SPKey.LAST_LOGIN_PHONE, ""));
            phoneEd.setSelection(phoneEd.getText().toString().length());
            txtGetVerification.setBackgroundResource(R.drawable.shape_btn_3cc051);
            txtGetVerification.setClickable(true);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void getUserRegisterforMobileCode(PasswordLogin passwordLogin) {
        if (passwordLogin.getErrCode() == 0) {
            //保存userinfo
            PasswordLogin.ResponseBean responseBean = passwordLogin.getResponse();
            UserInfoUtils.saveUserInfo(passwordLogin);
            //是否需要修改昵称
            int diyici = responseBean.getDiyici();
            //笔名
            String biName = responseBean.getBi_name();
            if (diyici == 1) {//未修改笔名
                SetPenNameActivity.toSetPenNameActivity(this, biName, responseBean.getAvatar());
            }
            //记录登录方式
            SPUtils.putPreferences(Constant.LOGIN_WAY, type);
            showKeyboard(false);
            setResult(RESULT_OK);
            finish();
        } else {
            toast(passwordLogin.getErrMsg());
        }
    }

    @OnTextChanged(value = R.id.phone_ed, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void titleTextChanged(Editable editable) {
        String s = editable.toString();
        txtGetVerification.setClickable(s.length() == 13);
        txtGetVerification.setBackgroundResource(s.length() == 13 ?
                R.drawable.shape_btn_3cc051 : R.drawable.shape_btn_8fe49d);
        if (s.length() == 13) {
            showKeyboard(false);
        }
    }

    @OnClick({R.id.layout_close, R.id.txtLoginRequest, R.id.txtGetVerification, R.id.txtPasswordLogin, R.id.iv_weixin, R.id.iv_xinlang, R.id.iv_qq})
    public void onViewClicked(View view) {
        showKeyboard(false);
        switch (view.getId()) {
            case R.id.layout_close:
                finish();
                break;
            case R.id.txtLoginRequest:
                startActivity(new Intent(this, LoginQuestionActivity.class));
                break;
            case R.id.txtGetVerification:
                if (!protocalSwitch.isChecked()) {
                    toast("请同意用户协议和隐私政策");
                    return;
                }
                Intent intent = new Intent(this, InputAuthCodeActivity.class);
                intent.putExtra(Constant.INTENT_DATA, phoneEd.getPhoneText());
                intent.putExtra(Constant.INTENT_TYPE, Constant.LOGIN_CODE);
                intent.putExtra(Constant.INTENT_CODE, netAuthCode);
                intent.putExtra(Constant.INTENT_MESSAGE, currentTimes);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.txtPasswordLogin:
                startActivityForResult(new Intent(this, PasswordLoginActivity.class), REQUEST_CODE);
                break;
            case R.id.iv_weixin:
                bindThirdAccount(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.iv_xinlang:
                bindThirdAccount(SHARE_MEDIA.SINA);
                break;
            case R.id.iv_qq:
                bindThirdAccount(SHARE_MEDIA.QQ);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                if (data != null && data.hasExtra(Constant.INTENT_MESSAGE)) {
                    currentTimes = data.getIntExtra(Constant.INTENT_MESSAGE, 0);
                    netAuthCode = data.getStringExtra(Constant.INTENT_CODE);
                    cutDownTime();
                } else {
                    setResult(RESULT_OK);
                    finish();
                }
            }
        }
    }

    /**
     * 第三方账号登录绑定
     */
    private void bindThirdAccount(SHARE_MEDIA shareMedia) {
        if (shareMedia == SHARE_MEDIA.SINA) {
            if (!Utils.isWBInstall(this)) {
                toast("\"新浪微博\"不可用\n请检查手机是否安装\"新浪微博\"");
                return;
            }
        }
        if (!XXPermissions.isHasPermission(this, mPermissionList)) {
            XXPermissions.with(this).permission(mPermissionList).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    UMShareAPI.get(VerificationCodeLoginActivity.this)
                            .deleteOauth(VerificationCodeLoginActivity.this, shareMedia, authListener);
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                }
            });
        } else {
            UMShareAPI.get(this).deleteOauth(this, shareMedia, authListener);
        }
    }


    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            if (map != null) {
                String open_id = "";
                //类别(1QQ 2微信 3微博)
                switch (share_media) {
                    case QQ:
                        type = 1;
                        open_id = map.get("openid");
                        break;
                    case WEIXIN:
                        type = 2;
                        open_id = map.get("openid");
                        break;
                    case SINA:
                        type = 3;
                        open_id = map.get("uid");
                        break;
                }
                //昵称
                String nickname = map.get("name");
                //头像
                //第三方授权返回的用户头像
                String headPortraits = map.get("iconurl");
                //手机号
                String mobile = null;
                //registrationid
                String registrationid = UserInfoUtils.getRegistrationId();
                //登录
                presenter.thirdPartyLogin(type, registrationid, open_id, nickname, headPortraits, mobile);
            } else {
                UMShareAPI.get(VerificationCodeLoginActivity.this).getPlatformInfo(VerificationCodeLoginActivity.this, share_media, authListener);
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            toast(throwable.getMessage());
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {

        }
    };

    //倒计时操作
    private void cutDownTime() {
        RxHelper.countdown(currentTimes)
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        currentTimes = integer;
                    }
                });
    }
}
